import 'package:flutter_hx/base/utils/toast_utils.dart';
import 'package:flutter_hx/model/address.dart';
import 'package:flutter_hx/network/HttpGo.dart';
import 'package:flutter_hx/router/app_pages.dart';
import 'package:flutter_hx/widgets/common_dialog.dart';
import 'package:get/get.dart';

class AddressListLogic extends GetxController {
  //{
  // 			"area": "",
  // 			"city": "",
  // 			"detailed": "",
  // 			"id": 0,
  // 			"isDefault": "",
  // 			"phone": "",
  // 			"province": "",
  // 			"realName": "",
  // 			"town": ""
  // 		}
  final addressList = RxList<Address>([]);

  ///是否在管理状态
  final isManaging = false.obs;

  ///切换管理状态按钮id
  final managingButtonId = "managing_button_id";

  @override
  void onInit() {
    getAddressList();
    super.onInit();
  }

  ///编辑地址
  toEdit(Address data) {
    Get.toNamed(Routes.addressEdit, arguments: data)?.then((value) {
      getAddressList();
    });
  }

  ///添加地址
  toAdd() {
    Get.toNamed(Routes.addressEdit)?.then((value) {
      getAddressList();
    });
  }

  ///切换管理状态
  switchManageMode() {
    isManaging.value = !isManaging.value;
    update([managingButtonId]);
  }

  ///切换默认地址
  setDefaultAddress(int? id, int index) async {
    if (id == null) return;
    final res = await HttpGo.instance
        .put("/address", data: addressList.value[index].toJson());
    res.ifSuccess((data) {
      addressList.value.map((e) {
        e.isDefault = "0";
        return e;
      });
      addressList.value[index].isDefault = "1";
      ToastUtils.show("更改改默认地址成功");
    });
    res.ifFailure((e) => e.toast());
  }

  ///删除地址
  deleteAddress(int? id) async {
    if (id == null) return;
    Get.dialog(CommonDialog(
      title: "删除地址",
      text: "是否确定删除地址",
      onConfirm: () async {
        final res = await HttpGo.instance.delete("/address/$id");
        res.ifSuccess((data) async {
          await getAddressList(afterDelete: () => {ToastUtils.show("删除成功")});
        });
        res.ifFailure((e) => e.toast());
      },
    ));
  }

  Future getAddressList({Function? afterDelete}) async {
    final res = await HttpGo.instance.get("/address");
    res.ifSuccess((data) {
      if (data is List) {
        addressList.value = data.map((e) => Address.fromJson(e)).toList();
      }
      afterDelete?.call();
    });
    res.ifFailure((e) => e.toast());
  }
}
